package com.wpp.websocket.config;

import com.wpp.websocket.handler.WsHandler;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.List;
import java.util.Map;

/**
 * @author thisisit
 * @class: WsInterceptor
 * @desc: TODO
 * @date: 2021/6/17 21:53
 */
public class WsInterceptor implements HandshakeInterceptor {
    @Override
    public boolean beforeHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Map<String, Object> map) throws Exception {
        //1 使用query参数 认证
        String query = serverHttpRequest.getURI().getQuery();
        System.out.println(query);

        boolean auth = false;
        //2 使用cookie中的指定字段认证
        if (serverHttpRequest instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest httpRequest = (ServletServerHttpRequest) serverHttpRequest;
            HttpHeaders headers = httpRequest.getHeaders();
            System.out.println(headers);
            List<String> cookie = headers.get("cookie");
            String cookieString = cookie.get(0);
            String[] split = cookieString.split(";");
            for (String s : split) {
                s = s.trim();
                if (s.startsWith("token=")) {
                    auth = true;
                    String substring = s.substring("token=".length());
                    System.out.println(substring);
                }
            }
            System.out.println(cookie);
        }
        if (auth) {
            if (webSocketHandler instanceof WsHandler) {

            }
        }
        return true;
    }

//    public String getTokenFromUrl(String url, String query) {
//
//    }
//    public String getToken(String source,String query){
//
//    }
//
//    public String getTokenFromCookie(List<String> s, String query) {
//
//    }

    @Override
    public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception e) {

        System.out.println("after");
    }
}
